#include "ModelWidget.h"

ModelWidget::ModelWidget(QWidget* parent)
{
	auto label = new QLabel("ttttt",this);
	label->setFixedSize(100, 200);
	m_mainLayout = new QVBoxLayout(this);
	m_title = new TitleWidget(this);
	m_stackedWidget = new QStackedWidget(this);
	m_mainLayout->addWidget(label);
	m_mainLayout->addWidget(m_title);
	m_mainLayout->addSpacing(100);
	m_mainLayout->addWidget(m_stackedWidget);
	setLayout(m_mainLayout);

	connect(m_title, &TitleWidget::signal_selectChanged, this, [&](QWidget* title)
	{
			if (auto widget = PageRelevancy::getInstance()->getRelevancyByParent(title))
			{
				m_stackedWidget->setCurrentWidget(widget);
			}
	});
}

void ModelWidget::addWidget(QWidget* title, QWidget* page)
{
	m_title->addItem(title);
	PageRelevancy::getInstance()->insertRelevancy(title, page);
	PageRelevancy::getInstance()->insertParent(page, this);
	m_stackedWidget->addWidget(page);
	if (auto pagetEle = dynamic_cast<PageElement*>(page))
	{
		connect(pagetEle, &PageElement::signal_leave, [&]()
			{
				m_title->reComeIn();
			});
	}
}

void ModelWidget::enter()
{
	PageRelevancy::getInstance()->setFocus(m_title);
	m_title->comeIn();
}

void ModelWidget::comeIn()
{
	m_title->comeIn();
	if (auto item = m_title->getFirstItem())
	{
		if (auto page = PageRelevancy::getInstance()->getRelevancyByParent(item))
		{
			m_stackedWidget->setCurrentWidget(page);
		}
	}
}

void ModelWidget::leave()
{
	m_title->clearAllFocus();
	for (const auto child : children())
	{
		if (auto page = dynamic_cast<PageElement*>(child))
		{
			page->leave();
		}
	}
}